﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Data;

using Rison.BusinessFacade.Common;
using Rison.DataAccess.Data.Biz;
using Rison.DataAccess.Common;
using Rison.BusinessFacade.Helper;
using Rison.BusinessFacade.Entity.Biz;

namespace Rison.BusinessFacade.Facade.Biz
{
    public enum InfoCategory
    {
        None,
        公告,
        纠风动态,
        纠风荟萃,
        专项治理,
        站所评议,
        最新诉求,
        最新回复,
        回复情况,
        访谈实录,
        在线访谈,
        预告,
        政府部门,
        服务窗口,
        行业,
        在线调查,
        网上测评,
        我有诉求
    }


    public sealed class DataSourceHelperFacade : FacadeBase
    {
        private InfoCategory _category = InfoCategory.None;

        protected override DataAccessBase dbObject
        {
            get
            {
                if (dbHelper == null)
                {
                    if (_category == InfoCategory.在线调查)
                        dbHelper = new DataSourceHelperDb(GlobalParams.Instance.ZXDCConnectionString);
                    else if (_category == InfoCategory.网上测评)
                        dbHelper = new DataSourceHelperDb(GlobalParams.Instance.WSCPConnectionString);
                    else if (_category == InfoCategory.我有诉求)
                        dbHelper = new DataSourceHelperDb(GlobalParams.Instance.WYSQConnectionString);
                    else
                        dbHelper = new DataSourceHelperDb(GlobalParams.Instance.NewsConnectionString);
                }

                return dbHelper;
            }
        }

        public DataSourceHelperFacade() { }

        public DataSourceHelperFacade(InfoCategory category)
        {
            _category = category;
        }

        protected override string identityFieldName
        {
            get { return "InfoID"; }
        }

        protected override List<SqlField> GetSqlFieldCollection(object value, bool getIdentityField)
        {
            throw new NotImplementedException();
        }

        protected override object SetPropertiesValue(DataRow row)
        {
            throw new NotImplementedException();
        }


        #region "   读取部门、诉求分类、发布的信息类别   "
        /// <summary>
        /// 读取部门
        /// </summary>
        /// <returns></returns>
        public DataSet GetDepartments()
        {
            return (dbObject as DataSourceHelperDb).GetDepartments(string.Empty);
        }
        public DataSet GetDepartments(string condition)
        {
            return (dbObject as DataSourceHelperDb).GetDepartments(condition);
        }

        /// <summary>
        /// 诉求的分类：投诉、意见建议、咨询、办事等
        /// </summary>
        /// <returns></returns>
        public DataSet GetSQCategory()
        {
            return (dbObject as DataSourceHelperDb).GetSQCategory();
        }

        /// <summary>
        /// 发布的信息的分类：公告、纠风动态等
        /// </summary>
        /// <returns></returns>
        public DataSet GetInfoCategory()
        {
            return (dbObject as DataSourceHelperDb).GetInfoCategory();
        }
        #endregion


        #region "  读取在线调查题目、保存调查结果  "
        public DataSet GetOnlineSurvey(List<Condition> conditions)
        {
            return (dbObject as DataSourceHelperDb).GetOnlineSurvey(ConditionConverter.ConvertToSqlConditionString(conditions));
        }

        /// <summary>
        /// 取得当前的在线调查题以及备选答案.
        /// </summary>
        /// <returns></returns>
        public DataSet GetCurrentOnlineSurvey()
        {
            return (dbObject as DataSourceHelperDb).GetCurrentOnlineSurvey();
        }

        public DataSet GetAllOnlineSurvey()
        {
            return (dbObject as DataSourceHelperDb).GetAllOnlineSurvey();
        }

        public DataSet GetAllAnswerbyID(string id)
        {
            return (dbObject as DataSourceHelperDb).GetAllAnswerbyID(id);
        }

        /// <summary>
        /// 保存调查结果
        /// </summary>
        /// <param name="answerIds"></param>
        /// <returns></returns>
        public bool CommitCurrentOnlineSurveyResult(List<string> answerIds, string ip, string browser)
        {
            int reVal = 0;
            dbObject.BeginTransaction();

            try
            {
                foreach (string id in answerIds)
                {
                    reVal = (dbObject as DataSourceHelperDb).UpdateOnlineSurveyResult(id, ip, browser);
                    if (reVal < 0)
                        break;
                }

                if (reVal < 0)
                    dbObject.RollBackTransaction();
                else
                    dbObject.CommitTransaction();

            }
            catch (Exception ex)
            {
                reVal = -1;
                string msg = ex.Message;
                dbObject.RollBackTransaction();
            }

            return reVal > 0;
        }
        #endregion


        #region "   保存我有诉求   "

        public bool PasswordExists(string password)
        {
            return (dbObject as DataSourceHelperDb).PasswordExists(password);
        }

        //public bool PasswordExistsNew(string password)
        //{
        //    return (dbObject as DataSourceHelperDb).PasswordExistsNew(password);
        //}

        //public DataSet GetWSCPbyPwd(string password)
        //{
        //    return (dbObject as DataSourceHelperDb).GetWSCPbyPwd(password);
        //}

        public DataRow GetsuqiuByPwd(string password)
        {
            return (dbObject as DataSourceHelperDb).GetsuqiuByPwd(password);
        }

        public bool SaveMyAppeal(MyAppeal o, Appealer user, List<SysAttachment> attachments, string attExplain)
        {
            lock (typeof(DataSourceHelperFacade))
            {
                int reVal = 0;
                StringBuilder sql = null;

                try
                {
                    dbObject.BeginTransaction();

                    if (string.IsNullOrEmpty(user.ID))
                        user.ID = Guid.NewGuid().ToString();
                    if (string.IsNullOrEmpty(o.Password))
                    {
                        //bool success = false;
                        //while (success == false)//确保密码没有重复
                        //{
                        //    //不采取随机数，采取yyyymmdd001
                        //    //o.Password = StringHelper.GetRadomString(GlobalParams.Instance.PasswordLength, false);
                        //    //success = !(dbObject as DataSourceHelperDb).PasswordExists(o.Password);

                        //}
                        o.Password = (dbObject as DataSourceHelperDb).GetPassword();
                    }

                    if (string.IsNullOrEmpty(o.ID))
                        o.ID = user.ID;
                    if (string.IsNullOrEmpty(o.CategoryMailboxRelID))
                        o.CategoryMailboxRelID = (dbObject as DataSourceHelperDb).GetDepartmentCategoryRelId(o.SendToTag);

                    sql = new StringBuilder();
                    sql.Append("insert into EMail (ID,Sender,Email,Phone,Address,ZipCode,FromType) values ");
                    sql.AppendFormat("('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", user.ID, user.Sender, user.Email, user.Phone, user.Address, user.ZipCode, user.FromType);

                    reVal = (dbObject as DataSourceHelperDb).SaveAppeal(sql.ToString());
                    if (reVal > 0)
                    {
                        int sxh = (dbObject as DataSourceHelperDb).GetSXH();
                        sql = new StringBuilder();
                        sql.AppendFormat("insert into Request (ID,MailBoxID,Type,RequestType,SendToType,SendToTag,SendToName,CategoryMailboxRelID,Title,Content,SubmitTime,Status,IsPublished,BackNvarchar2,BackNvarchar3,Password,BackNvarchar,BackNvarchar1) values ");
                        sql.AppendFormat("('{0}','{1}','{2}','我有诉求','{3}','{4}','{5}','{6}','{7}','{8}',getdate(),'UNOPERATE','0','{9}','{10}','{11}','{12}','{13}')", o.ID, o.MailBoxID, o.Type, o.SendToType, o.SendToTag, o.SendToName, o.CategoryMailboxRelID, o.Title, o.Content, o.BackNvarchar2, o.BackNvarchar3, o.Password, Convert.ToInt32(o.BackNvarchar).ToString(), sxh.ToString("0000"));

                        reVal = (dbObject as DataSourceHelperDb).SaveAppeal(sql.ToString());
                    }

                    if (reVal > 0 && attachments != null)
                    {
                        foreach (SysAttachment a in attachments)
                        {
                            sql = new StringBuilder();
                            sql.Append("insert into UploadFile (ID,RequestID,PhysicalName,DisplayName,FileSize,UploadTime,BackNvarchar) values ");
                            sql.AppendFormat("('{0}','{1}','{2}','{3}','{4}',getdate(),'{5}')", Guid.NewGuid().ToString(), o.ID, a.FilePath, a.FileName, a.FileSize, attExplain);

                            reVal = (dbObject as DataSourceHelperDb).SaveAppeal(sql.ToString());

                            if (reVal < 0) break;
                        }
                    }

                    if (reVal > 0)
                        dbObject.CommitTransaction();
                    else
                        dbObject.RollBackTransaction();

                }
                catch
                {
                    reVal = -1; dbObject.RollBackTransaction();
                }
                finally
                {
                    sql = null;
                }

                return reVal > 0;
            }
        }
        #endregion


        public DataSet GetTopNumInfos(int topNum)
        {
            return GetTopNumInfos(_category, topNum);
        }

        public DataSet GetTopNumInfos(int topNum, int subjectLength)
        {
            return GetTopNumInfos(_category, topNum, subjectLength);
        }

        public DataSet GetTopNumInfos(InfoCategory categoryId, int topNum)
        {
            return (dbObject as DataSourceHelperDb).GetTopNumInfos(Convert.ToInt32(categoryId), topNum);
        }

        public DataSet GetTopNumInfos(InfoCategory categoryId, int topNum, int subjectLength)
        {
            return (dbObject as DataSourceHelperDb).GetTopNumInfos(Convert.ToInt32(categoryId), topNum, subjectLength);
        }

    }
}
